<?php require_once '../yubico-php-lib/AES128.php';

$devMode = true;
$debug = true;
//$announcement = 'Site under maintenance, will be back in a few hours...';
$announcement = '';

if (! $debug && isset($appname)) { // Initialized
	return;
} else { // Initialize it
	if (file_exists('/WINDOWS/system32')) { // I do dev on Windows
		$devMode = true;
	}
}

///////////// Customize these ///////////////
//

///
$appname = 'yms';

if ($devMode) { // Customize to your development environment
    //$domain = 'http://localhost';
    $domain = 'http:///yubico/';
    $webroot = '/Apache2.2/htdocs/yms/';
    $appssl = $domain.'/'.$appname.'/';
} else {
    //$domain = 'http://api.yubico.com';
    $domain = 'http:///yubico/';
    $webroot = '/root/w/';
    #$appssl = 'https://api.yubico.com/'.$appname;
    $appssl = $domain.'/'.$appname.'/';
}

$appurl = $domain.'/'.$appname.'/';

// Put your affiliate link here
define('YUBICO_AFF_LINK', 'http://yubico.com/products/order/');

// Database related
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'yubico';

//
///////////// End Customization //////////////

define('MAX_PER_PAGE', 100);
define('ROOT_ONLY', 'Only root admin is allowed here!');
define('BACK_BUTTON', "<input type=button Value=Back onClick='history.back()'>");
define('BACK_AGAIN', "Check input or try again later");
define('BACK_AGAIN_BUTTON', BACK_AGAIN."<p>".BACK_BUTTON);
define('LOGIN_FIRST', 'Login or Sign Up First');
define('TIMEDOUT', 'Session timed out! Login first.');
define('A_MONTH_IN_SECS', 2592000);
define('LOGO', '<a href=http://yubico.com><img src=images/trust_the_net.jpg border=0></a>');
define('LOGOLINK', '<a href='.$appssl.'> '.
		'<img title="Yubikey Management System" src=images/trust_the_net.jpg border=0></a>');
define('MAX_FAILS', 3);
define('MAX', 45);
define('MAX_NOTE', 100);
define('DEF_TIMEOUT_IN_SECS', 86400);
define('PW_MIN', 4);
define('PW_MAX', 50);
define('NOT_YET', 'Not implemented, coming soon...');

function writeLog($msg, $debug=false) {
	global $devMode;
	$writeIt = true;
	if ($debug && !$devMode) {
		$writeIt = false;
	}
	if ($writeIt) {
    	$fileMsg = date( 'Y-m-d H:i:s: ').trim($msg);
    	if (isset($_SERVER['REMOTE_ADDR'])) {
    		$fileMsg .= ' by '.$_SERVER['REMOTE_ADDR'];
    	}
   		$fileMsg .= "\n";
		error_log($fileMsg, 3, "/tmp/yms.log");
	}
}

function logoff() {
	// Unset all of the session variables.	
	if (!isset($_SESSION['usrid'])) {
		return;
	}
	$usrid = $_SESSION['usrid'];
	
	addHist($usrid, 'logoff');
	unset($_SESSION['usrid']);
	unset($_SESSION['hi']);
	unset($_SESSION['client']);
	$_SESSION = array();

	// If it's desired to kill the session, also delete the session cookie.
	// Note: This will destroy the session, and not just the session data!
	if (isset($_COOKIE[session_name()])) {
    	setcookie(session_name(), '', time()-42000, '/');
	}

	session_destroy();
}

function alert($msg) {
	echo "<script language=Javascript>\n".
		"<!--\n". 
		"alert ('".$msg."')\n". 
		"//-->\n".
		"</script>\n";
}

function unescape($s) {
	return str_replace('\\', "", $s);
}

function getUsrIdFromCookie() {
	if (isset($_COOKIE['usrid']) && 
		($usrid=aesDecrypt($_COOKIE['usrid'])) > 0) {
       	return $usrid;
 	} else {
 		return 0;	
 	}
}

function getTab() {
        if (isset($_SESSION['tab']) && ($tab=$_SESSION['tab']) > 0) {
                return $tab;
        } else {
                return ($_SESSION['tab'] = 0);
        }
}

function getUsrIdFromSession() {
	if (isset($_SESSION['usrid']) && ($usrid=$_SESSION['usrid']) > 0) {
		if (isset($_SESSION['timeout']) && $_SESSION['timeout'] > 0) {
		  if (time() - $_SESSION['last'] > $_SESSION['timeout']) {
			unset($_SESSION['usrid']);
			unset($_SESSION['email']);
			unset($_SESSION['timeout']);
			$_SESSION['alert']= TIMEDOUT;
			writeLog('! TIMEOUT !');
			return 0;
		  }
		  $_SESSION['last'] = time();
		}
		return $usrid;
	} else {
		return 0;
	}
}

// Check str
function isHack($in) {
	global $admEmail;
	$r = false;
	if (strpos($in, "'") !== false) {
		$r = true;
	}
	if ($r) {
		$msg = 'Hack ['.$in.'] from '.$_SERVER['REMOTE_ADDR'];	
		writeLog($msg);
		sendMail($admEmail, $msg, $msg, $admEmail);
	}
	return $r;
}

function getHttpVal($key, $defaultVal) {
	$val = $defaultVal;
	if (array_key_exists($key, $_GET)) {
		$val = $_GET[$key];
  	} else if (array_key_exists($key, $_POST)) {
  		$val = $_POST[$key];
  	}
  	//return unescape(trim($val));
  	$v = unescape(trim($val));
  	return $v;
}

///////////////////// 
//
// DB Related
// 
///////////////////

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $conn) or die('Could not select database');

function query($q) {
	global $conn;
	$result = mysql_query($q, $conn);
	if (!$result) {
		$err = "Invalid query -- $q -- ";
		writeLog($err);
		die($err . mysql_error());
	}
	return $result;
}

function beginTx() {
	global $conn;
	mysql_query("BEGIN", $conn); 
}

function rollbackTx() {
	global $conn;
	mysql_query("ROLLBACK", $conn); 
}

function commitTx() {
	global $conn;
	mysql_query("COMMIT", $conn); 
}

function mysql_quote($value) {
	return "'" . mysql_real_escape_string($value) . "'";	
}

// Substr after $ch in $s
// returns paul from paul@yubico.com
function strBefore($s, $ch) {
    if (($pos = strpos($s, $ch)) !== false) {
        return substr($s, 0, $pos);
    } else {
        return $s;
    }
}

// Substr before $ch in $s
// returns yubico.com from paul@yubico.com
function strAfter($s, $ch) {
    if (($pos = strpos($s, $ch)) !== false) {
        return substr($s, $pos+1, strlen($s) - 1);
    } else {
        return $s;
    }
}

function getImg($title, $fname) {
    return '<img border=0 title="'.$title.'" src=images/'.$fname.'>';
}

function makePopupURL($url, $name, $h, $color='', $title='') {
  $u = '<a href="' . makePurePopupURL($url, $name, $h).'" ';
  $u .= ' title="'.$title.'" ';
  $u .= ' name=' . strBefore($url, '.php');
  $u .= '>';
  if (strlen($color) > 0) {
  	$u .= '<font color='.$color.'>';
  }
  $u .= $name . '</a></font>';
  return $u;	
}

function makePurePopupURL($url, $name, $h) {
    return 'javascript:popup(\'' . $url . '\','. $h . ')';
}

function truncate($s, $max) {
    return (strlen($s) > $max) ? substr($s, 0, $max-3).'...' : $s;
}

function addHist($usrid, $note, $keyid=0, $client=0) {
	$s = truncate($note, MAX);
	$stmt = 'INSERT INTO history (usrid, note, ip, keyid, creation) VALUES ('.
		$usrid.','.
		mysql_quote($s).','.
		mysql_quote($_SERVER['REMOTE_ADDR']).','.
		$keyid.','.
		'NOW())';
	query($stmt);
}

function sendMail($to, $subj, $mesg, $from, $cc='') {
	global $devMode, $admEmail;
	if ($devMode) {
		writeLog('Email subj: '.$subj.' To: '.$to.' From: '.$from.' CC: '.$cc.' Body: '.$mesg);
		return true;
	}
	$headers = 'From: '.$from. "\r\n";
	$headers .= 'Bcc: ' . $admEmail . "\r\n";
//	if (strlen($cc) > 0) {
		$headers .= 'CC: ' . $cc . "\r\n";
//	}
	if (!mail($to, $subj, $mesg, $headers)) {
		writeLog('FAILED email to:'.$to.' subj: '.$subj);		
		return false;
	} else {
		return true;
	}
}

function validEmail($e) {
	if (strlen($e) > 4 && strpos($e,"@") > 0 && strlen($e) < MAX && 
		strpos($e,"@") < strrpos($e,"."))
    {
    	$a = count_chars($e, 1);    
    	if ($a[ord('@')] != 1 || isHack($e)) {
    		return false;
    	}
    	return true;
    }   
    
    return false;
}

function setAcctLastAccessByID($adminId) {
	$stmt = 'UPDATE admin SET last_access=NOW() WHERE id='.$adminId;
	query($stmt);
}

// Timeout in secs
function setTimeoutByID($usrid, $timeout) {
	$stmt = 'UPDATE users SET timeout='.$timeout.' WHERE usrid='.$usrid;
	query($stmt);
}

function showAcctDisabled() {
	global $admEmail;
	echo '<center><h3>Your account is temporarily suspended, please contact '.
		'<a href=mailto:'.$admEmail.'>the site administrator</a></h3>.';
}

function spaces($n) {
	for ($i=0; $i < $n; $i++) {
		echo '&nbsp; ';
	}
}

function urlize($url, $name, $new=true) {
	$u = '<a href='.$url;
	if ($new) {
		$u .= ' target=_new';
	}
	$u .= '>'.$name.'</a>';
	return $u;
}

function getAlert() {
  $alert = '';
  if (isset($_SESSION['alert'])) {
	$alert = $_SESSION['alert'];
	unset($_SESSION['alert']);
  }
  return $alert;
}

// Show a line of <tr> alert </tr>
function showAlert($alert) {
	if (strlen($alert) < 2) { return; }
	echo '<div align=center width=70% id=ALERT style="margin-top:5px;">';
	echo '<span class=headerTextR>';
	if (stripos($alert, 'success') === false) {
		echo '<font size=+1><br>'.getImg('','warn.gif');
	}
	echo ' '.$alert.'</font></span>';
	echo '</div>';
}

function divBut($w, $href, $name, $hilight=false) {
  echo '<div style="border:1px green solid;width:'.$w.'px;text-align:center;';
  if ($hilight) { echo 'background-color:#008080;'; }
  echo '"><font size=1>';
  if (!$hilight) { echo '<a href='.$href.'>'; }
  if ($hilight) { echo '<font color=#FFFFFF>'; }
  echo $name;
  if ($hilight) { echo '</a>'; }
  echo '</div>';
}

function getClientEmail($client) {
	$stmt = 'SELECT email FROM clients WHERE id='.$client;
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		$e = $row['email'];		
		mysql_free_result($r);
		$a = explode(" ", $e);
		return $a[0];
	}
	return '';
}

function updClientPerm($client, $perm) {
	$stmt = 'UPDATE clients SET perm_id='.$perm.' WHERE id='.$client;
	//writeLog('updClientPerm> '.$stmt);
	query($stmt);
}

function getClientPerm($client) {
	$stmt = 'SELECT perm_id FROM clients WHERE id='.$client;
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {		
		mysql_free_result($r);
		return $row['perm_id'];
	}
	return 0;
}

function getClientByEmail($email) {
	$stmt = 'SELECT id FROM clients WHERE email='.mysql_quote($email);
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		return $row['id'];
	}
	return -1;
}

$admEmail = getClientEmail(1);
$mailAdm = '<a href="mailto:'.$admEmail.'">'.$admEmail.'</a>';
$contactAdm = 'Contact ' . $admEmail;

function genAPIKey() {
	$rnd = hash('sha1', rand(999,99999999));
   	return base64_encode(AES128::fromHexString($rnd));
}

function genStrongPw() {
	$h = hash('sha1', rand(999,99999999));	 
   	$s = base64_encode(AES128::fromHexString($h));
	//$s = ModHex::encode($h);
   	return substr($s, 3, 15);
}

function isRootAdm() {
	if (!isset($_SESSION['client'])) {
		logoff();
	}
	return $_SESSION['client'] == 1 ? true : false;
}

// If passing $client = -1, that means all clients, same for $active. 
function numOfYubikeys($client, $active) {
	$stmt = 'SELECT COUNT(*) AS C FROM yubikeys';
	if ($client >= 0) {
		$stmt .= ' WHERE client_id='.$client;
	}
	if ($active >= 0) {
		$stmt .= (($client >= 0) ? ' AND' : ' WHERE');
		$stmt .= ' active='.$active;
	}
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		return $row['C'];
	} else {
		return 0;
	}
}

// Return an array of full client info eg. how many active|inactive yubikeys owned by this client
// $a['num_active'], $a['num_inactive'], plus the entire row
function getClientInfo($client) {
	$a = array();
	$a['num_active'] = numOfYubikeys($client, 1);
	$a['num_inactive'] = numOfYubikeys($client, 0);
	
	$stmt = 'SELECT * FROM clients WHERE id='.$client;
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		$a = array_merge($a, $row);
	}
	
	return $a;
}

function showKeyStateSelectBox($name, $state) {
	global $admEmail;
	echo '<select name='.$name.'>';
	switch ($state) {
		case 0: return 'Inactive'; break;
		case 1: return 'Active'; break;
		default: return 'Unknown'; break;
	}
	echo '</select>';
}

function explainPerm($perm) {
        global $contactAdm;
        switch ($perm) {
                case 1: return 'Verify OTP, Manage clients, Manage keys';
                case 2: return 'Verify OTP, Manage keys';
                case 3: return 'Verify OTP';
                default: return 'Unknown! '.$contactAdm;
        }
}

function replaceInTemplate($inFname, $strs) {
    $in = fopen($inFname, "r");
    $content = fread($in, filesize($inFname));
    fclose($in);
    foreach (array_keys($strs) as $srch) {
        $content = str_replace($srch, $strs[$srch], $content);
    }
    return $content;
}

function getGroupName($groupId) {
	//select group_name from groups where group_id = 1
	$stmt = 'SELECT group_name FROM groups WHERE group_id='.$groupId;
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		return $row['group_name'];
	}
	
	return "Demo";
}

function getGroupId($groupName) {
	//select group_name from groups where group_id = 1
		
	$stmt = 'SELECT group_id FROM groups WHERE group_name='.mysql_quote($groupName);
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		return $row['group_id'];
	} else {
		$client = $_SESSION['client'];
		$notes = 'Added by '.$client;
		$stmt = 'INSERT INTO groups (client_id, group_name, notes) '.
			'VALUES ('.$client.','.mysql_quote($groupName).','.mysql_quote($notes).')';
		if ($r = query($stmt)) {
          return mysql_insert_id();   	
        }
	}
	
	return 2;
}

function getPolicyNames($client) {
	$a = array();
	$stmt = 'SELECT policy_name FROM userimportconf uconf WHERE (uconf.policy_id in (select policy_id from clientpolicymap c WHERE c.client_id='.$client.'))';
	$r = query($stmt);

	while ($row=mysql_fetch_assoc($r)) {
		array_push($a, $row['policy_name']); 
    }
    mysql_free_result($r);
	
	return $a;
}

// If passing $client = -1, that means all clients, same for $active. 
function numOfUsers($client, $active) {
	$stmt = 'SELECT COUNT(*) AS C FROM users';
	if ($client >= 0) {
		$stmt .= ' WHERE client_id='.$client;
	}
	if ($active >= 0) {
		$stmt .= (($client >= 0) ? ' AND' : ' WHERE');
		$stmt .= ' user_status='.$active;
	}
	$r = query($stmt);
	if ($row=mysql_fetch_assoc($r)) {
		mysql_free_result($r);
		return $row['C'];
	} else {
		return 0;
	}
}

// Return an array of full client user info eg. how many active|inactive users owned by this client
// $a['num_active'], $a['num_inactive']
function getClientUserInfo($client) {
	$a = array();
	$a['num_active'] = numOfUsers($client, 1);
	$a['num_inactive'] = numOfUsers($client, 0);
	return $a;
}

function getClientUserKeyInfo($client) {
	$a = array();
	$a['num_active_user'] = numOfUsers($client, 1);
	$a['num_active_key'] = numOfYubikeys($client, 1);
	return $a;
}

?>
